import {useEffect} from "react";
import {Card, Table} from "antd";
import {Link} from "react-router-dom";
import TableToolbar from "@/common/table/TableToolbar.tsx";
import LogFactory from "@/log/LogFactory.ts";
import {useAppDispatch, useAppSelector} from "@/redux/hook.tsx";
import BaseEntity from "@/type/BaseEntity";
import {StatePageType} from "@/redux";
import {AsyncThunk} from "@reduxjs/toolkit";
import {JsonResult, PagingData, PagingResult} from "@/http";
import {ColumnsType} from "antd/es/table";
import {StoreKeys} from "@/redux/store.ts";

interface IProps<T extends BaseEntity> {
    /** Pro表格标题 */
    title: string,
    /**
     * redux 存储库的名字,但实际一定要继承StatePageType<T>
     */
    storeName: StoreKeys<T>;
    /**
     * 执行表格分页数据获取的异步action
     */
    action: AsyncThunk<JsonResult<PagingResult<T>>, PagingData, any>,
    /**
     * 表格列渲染数据
     */
    columns: ColumnsType<T>,
    /**
     * 右上角按钮url
     */
    extraUrl?: string,
    /**
     * 右上角按钮标题
     */
    extraTitle?: string,
}

const log = LogFactory.getLogger("ProTable");
/**
 * antd 表格增强组件
 * @param props 表格属性
 */
const ProTable =<T extends BaseEntity> (props: IProps<T>) => {
    const {columns } = props;
    const dispatch = useAppDispatch();
    const store = useAppSelector(state => state[props.storeName]) as unknown as StatePageType<T>;

    const pageChange = async (page: number, pageSize: number) => {
        log.debug("分页切换: page = ", page, ", pageSize = ", pageSize);
        dispatch(props.action({page, pageSize}));
    }
    useEffect(() => {
        dispatch(props.action({page: store.currentPage, pageSize: store.pageSize}));
    }, []);


    const refreshTableData = () => {
        dispatch(props.action({page: store.currentPage, pageSize: store.pageSize}));
    }

    const onSearch = (value: string) => {
        log.debug("用户索引值: ", value)
    }

    return (
        <Card title={props.title} extra={ <Link to={props.extraUrl ?? ".."}>{props.extraTitle ?? "反回上一页"}</Link> } style={{overflowX: "hidden"}}>
            <TableToolbar
                refresh={refreshTableData}
                onSearch={onSearch}
                infoValue={store.total}
            />
            <Table<T>
                loading={store.loading}
                scroll={{
                    x: 1200,
                }}
                dataSource={store.data}
                columns={columns}
                pagination={{
                    onChange: pageChange,
                    current: store.currentPage,
                    pageSize: store.pageSize,
                    total: store.total,
                    showQuickJumper: true,
                }}
            />
        </Card>
    );
};

export default ProTable;